package com.siyoumi.app.modules.app_book.service;

import com.siyoumi.app.entity.*;
import com.siyoumi.app.modules.app_book.service.handle_order.BookOrderHandle20FunDown;
import com.siyoumi.app.modules.app_book.service.handle_order.BookOrderHandle90SharePrice;
import com.siyoumi.app.modules.app_book.vo.*;
import com.siyoumi.app.modules.fun.service.SvcFun;
import com.siyoumi.app.modules.fun.vo.VaFunAdd;
import com.siyoumi.app.modules.sms.service.SvcSms;
import com.siyoumi.app.modules.sms.vo.VoSmsSend;
import com.siyoumi.app.modules.user.service.SvcSysSale;
import com.siyoumi.app.modules.user.service.SvcSysUser;
import com.siyoumi.app.modules.user.vo.VoSaleAddRecord;
import com.siyoumi.app.service.*;
import com.siyoumi.app.sys.service.wxapi.WxApiPay;
import com.siyoumi.component.LogPipeLine;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//订单
@Slf4j
@Service
public class SvcBookOrder
        implements IWebService {
    static public SvcBookOrder getBean() {
        return XSpringContext.getBean(SvcBookOrder.class);
    }

    static public BookOrderService getApp() {
        return BookOrderService.getBean();
    }

    //public String getStatus(BookOrder entity, EnumBookOrderStatus enumOrderStatus) {
    //    if (entity.getBorder_refund() == 1) { //已退款
    //        if (entity.getBorder_status() <= 10) {
    //            return "已退款";
    //        }
    //    }
    //    return enumOrderStatus.get(entity.getBorder_status());
    //}

    public BookRefundOrder getEntityRefund(String orderId) {
        JoinWrapperPlus<BookRefundOrder> query = listRefundQuery();
        query.eq("brefo_order_id", orderId);

        return BookRefundOrderService.getBean().first(query);
    }

    /**
     * 分帐订单
     *
     * @param inputData
     */
    public JoinWrapperPlus<BookOrder> listSaleQuery(InputData inputData) {
        JoinWrapperPlus<BookOrder> query = SvcBookOrder.getBean().listQuery(inputData);
        query.eq("border_enable", 1) //有效订单
                .in("border_status", 0, 5, 10, 15, 20); //待支付-退房
        return query;
    }

    /**
     * 获取是否存在有效订单
     *
     * @param uid
     */
    public Boolean existOrderFirstEnable(String uid) {
        JoinWrapperPlus<BookOrder> query = listQuery();
        query.eq("border_uid", uid).eq("border_enable", 1);
        query.select("border_uid");
        return getApp().firstMap(query) != null;
    }

    public JoinWrapperPlus<BookOrder> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<BookOrder> listQuery(InputData inputData) {
        String id = inputData.input("id");
        String phone = inputData.input("phone");
        String userName = inputData.input("user_name");
        String spuId = inputData.input("spu_id");
        String status = inputData.input("status");
        String refund = inputData.input("refund");
        String handle = inputData.input("handle");
        String shareSalesHandle = inputData.input("share_sales_handle");
        String uidSale = inputData.input("uid_sale");
        String createBegin = inputData.input("create_begin");
        String createEnd = inputData.input("create_end");
        String continueOrder = inputData.input("continue_order");
        String continueMainId = inputData.input("continue_main_id");

        JoinWrapperPlus<BookOrder> query = getApp().join();
        query.eq("border_x_id", XHttpContext.getX());
        if (XStr.hasAnyText(id)) { //订单号
            query.eq("border_id", id);
        } else if (XStr.hasAnyText(uidSale)) { //分销员ID
            query.eq("border_share_sales_uid", uidSale);
        } else if (XStr.hasAnyText(continueMainId)) { //主订单ID
            query.eq("border_continue_main_id", continueMainId);
        } else {
            if (XStr.hasAnyText(continueOrder)) { //续单
                query.eq("border_continue", continueOrder);
            }
            if (XStr.hasAnyText(phone)) { //手机号
                query.eq("border_user_phone", phone);
            }
            if (XStr.hasAnyText(userName)) { //姓名
                query.like("border_user_name", userName);
            }
            if (XStr.hasAnyText(spuId)) { //房源
                query.eq("border_spu_id", spuId);
            }
            if (XStr.hasAnyText(refund)) { //申请退款状态
                query.eq("border_refund", refund);
            }
            if (XStr.hasAnyText(status)) { //订单状态
                if ("all".equals(status)) {
                    query.between("border_status", 0, 20);
                } else {
                    query.eq("border_status", status);
                }
            }
            if (XStr.hasAnyText(handle)) { //分帐处理状态
                if ("all".equals(handle)) {
                    query.in("border_handle", 0, 1);
                } else {
                    query.eq("border_handle", handle);
                }
            }
            if (XStr.hasAnyText(shareSalesHandle)) { //主播分账处理状态
                if ("all".equals(handle)) {
                    query.in("border_share_sales_handle", 0, 1, 10);
                } else {
                    query.eq("border_share_sales_handle", shareSalesHandle);
                }
            }
            if (XStr.hasAnyText(createBegin) && XStr.hasAnyText(createEnd)) { //创建时间
                LocalDateTime b = XDate.parse(createBegin);
                LocalDateTime e = XDate.parse(createEnd);

                query.between("border_create_date", b, e);
            }
        }

        return query;
    }

    public JoinWrapperPlus<BookRefundOrder> listRefundQuery() {
        return listRefundQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<BookRefundOrder> listRefundQuery(InputData inputData) {
        String orderId = inputData.input("order_id");
        String auditStatus = inputData.input("audit_status");

        JoinWrapperPlus<BookRefundOrder> query = BookRefundOrderService.getBean().join();
        query.eq("brefo_x_id", XHttpContext.getX());
        if (XStr.hasAnyText(orderId)) { //订单号
            query.eq("brefo_order_id", orderId);
        } else {
            if (XStr.hasAnyText(auditStatus)) { //申请退款状态
                query.eq("brefo_audit_status", auditStatus);
            }
        }

        return query;
    }

    /**
     * 库存加减操作
     *
     * @param entitySpu  房间
     * @param dateBegin  开始日期
     * @param dateEnd    结束日期
     * @param stockCount 【2】扣2库存；【-1】增加1库存
     */
    public void stockHandle(BookSpu entitySpu, LocalDateTime dateBegin, LocalDateTime dateEnd, Integer stockCount) {
        LogPipeLine log = LogPipeLine.ofSys();
        log.setLogMsgFormat("开始扣库存->添加每日库存记录，日期：{0} - {1}"
                , XDate.toDateString(dateBegin)
                , XDate.toDateString(dateEnd));
        {
            VaBookSpuDay vaBookSpuDay = new VaBookSpuDay();
            vaBookSpuDay.setBspud_spu_id(entitySpu.getKey());
            vaBookSpuDay.setBegin_date(dateBegin);
            vaBookSpuDay.setEnd_date(dateEnd);
            vaBookSpuDay.setBspud_spu_add_price(null);
            vaBookSpuDay.setBspud_stock_add(null);
            SvcBookSpu.getBean().dayEditBatch(vaBookSpuDay);
        }
        log.setLogMsg("开始扣库存->批量扣库存：" + stockCount);
        {
            VaBookSpuDayUpdateStock updateStock = VaBookSpuDayUpdateStock.of(entitySpu.getKey(),
                    dateBegin, dateEnd, stockCount);
            SvcBookSpu.getBean().dayBatchUpdateStock(updateStock);
        }
    }

    /**
     * 库存检查
     *
     * @param entitySpu
     * @param dateBegin
     * @param dateEnd
     * @param stockCount
     */
    public XReturn stockCheck(BookSpu entitySpu, LocalDateTime dateBegin, LocalDateTime dateEnd, Integer stockCount) {
        //检查库存
        List<SpuDayData> listDay = SvcBookSpu.getBean().listDay(entitySpu, dateBegin, dateEnd);
        XHttpContext.set("list_day", listDay);

        List<SpuDayData> listDayLeft = listDay.stream().filter(item -> item.getLeft_total() < stockCount).collect(Collectors.toList());
        if (!listDayLeft.isEmpty()) { //存在库存不足的日期
            List<String> dayStr = listDayLeft.stream().map(item -> XDate.toDateString(item.getDate())).collect(Collectors.toList());
            return XReturn.getR(20111, "库存不足，" + dayStr);
        }

        return EnumSys.OK.getR();
    }

    /**
     * 能否下单
     *
     * @param vo
     * @param editOrder 【true】修改订单
     * @return
     */
    public XReturn orderCan(VoBookOrder vo, Boolean editOrder) {
        LogPipeLine log = LogPipeLine.ofSys();
        //房源
        BookSpu entitySpu = SvcBookSpu.getApp().getEntity(vo.getSpu_id());
        XValidator.isNull(entitySpu, "spu_id error");
        XValidator.err(SvcBookSpu.getBean().valid(entitySpu));
        if (vo.getSet_user_count() < vo.getSpu_count()) {
            return XReturn.getR(20071, "每个房间至少要有1人用餐");
        }

        Integer setLimitMin = entitySpu.getBspu_set_limit_min() * vo.getSpu_count();
        Integer setLimitMax = entitySpu.getBspu_set_limit_max() * vo.getSpu_count();
        if (vo.getSet_user_count() < setLimitMin) {
            return XReturn.getR(20080, XStr.format("用餐人数不能小于{0}人数", setLimitMin.toString()));
        }
        if (vo.getSet_user_count() > setLimitMax) {
            return XReturn.getR(20081, XStr.format("用餐人数不能大于{0}人数", setLimitMax.toString()));
        }

        //sku
        BookSku entitySku = SvcBookSku.getBean().getEntitySku(entitySpu.getKey(), vo.getDay_count());
        XValidator.isNull(entitySku, "房间未配置sku");
        if (vo.getContinue_order()) {
            //结单不需要检查sku
        } else {
            if (!vo.getSku_id().equals(entitySku.getKey())) {
                return XReturn.getR(20101, "sku配置有变动，请刷新页面再试");
            }
        }
        //套餐
        BookSet entitySet = SvcBookSet.getApp().getEntity(vo.getSet_id());
        XValidator.isNull(entitySet, "套餐ID异常");
        XValidator.err(SvcBookSet.getBean().valid(entitySet));
        if (!entitySet.getBset_store_id().equals(entitySpu.getBspu_store_id())) {
            return XReturn.getR(20111, "套餐商家ID异常");
        }
        //
        LocalDateTime dateBegin = vo.getDate_begin();
        LocalDateTime dateEnd = vo.getDate_begin().plusDays(vo.getDay_count() - 1);
        log.setLogMsgFormat("日期：{0} - {1}", dateEnd.toString(), dateEnd.toString());
        //
        if (!editOrder) {
            //检查库存
            {
                XReturn r = stockCheck(entitySpu, dateBegin, dateEnd, vo.getSpu_count());
                if (r.err()) {
                    return r;
                }
            }
            List<SpuDayData> listDay = XHttpContext.get("list_day");
            //
            //检查工厂检查
            {
                BookOrderHandle orderHandle = BookOrderHandle.of();
                orderHandle.setVo(vo);
                orderHandle.setListDay(listDay);
                XReturn r = orderHandle.orderBeforeCheck();
                if (r.err()) {
                    return r;
                }
            }
        }
        //
        return EnumSys.OK.getR();
    }

    /**
     * 下单
     *
     * @param vo
     */
    public XReturn order(VoBookOrder vo) {
        LogPipeLine log = LogPipeLine.ofSys();
        log.setLogMsg(vo);
        //
        XValidator.err(orderCan(vo, false));
        //
        BookSpu entitySpu = SvcBookSpu.getApp().getEntity(vo.getSpu_id());
        //商家
        BookStore entityStore = SvcBookStore.getApp().getEntity(entitySpu.getBspu_store_id());
        XValidator.err(SvcBookStore.getBean().valid(entityStore));
        if (vo.getPay_deposit() == 1) {
            if (entityStore.getBstore_deposit_enable() == 0) {
                return XReturn.getR(20091, "商家未开启支付订金");
            }
        }
        if (vo.getContinue_order()) {
            if (XStr.isNullOrEmpty(vo.getContinue_main_id())) {
                return XReturn.getR(20101, "缺少主订单号");
            }

            BookOrder entityOrderContinue = getApp().getEntity(vo.getContinue_main_id());
            XValidator.isNull(entityOrderContinue, "主订单号异常");
        }
        //
        BookSku entitySku = SvcBookSku.getApp().getEntity(vo.getSku_id());
        BookSet entitySet = SvcBookSet.getApp().getEntity(vo.getSet_id());
        List<SpuDayData> listDay = XHttpContext.get("list_day");
        //
        BookOrderHandle orderHandle = BookOrderHandle.of();
        orderHandle.setVo(vo);
        orderHandle.setListDay(listDay);
        //
        LocalDateTime dateBegin = vo.getDate_begin();
        LocalDateTime dateEnd = vo.getDate_begin().plusDays(vo.getDay_count() - 1);
        //
        //开始下单
        return XApp.getTransaction().execute(status -> {
            SvcBookSpu.getApp().getEntityLock(entitySpu.getKey()); //锁房间
            //扣库存
            stockHandle(entitySpu, dateBegin, dateEnd, vo.getSpu_count());
            //
            BookOrder entityOrder = new BookOrder();
            entityOrder.setBorder_x_id(XHttpContext.getX());
            entityOrder.setBorder_id(XApp.getStrID("OA"));
            entityOrder.setBorder_uid(getUid());
            entityOrder.setBorder_uid_order(entityOrder.getBorder_uid());
            if (XStr.hasAnyText(vo.getSale_uid())) { //代下单
                entityOrder.setBorder_uid_order(vo.getSale_uid());
            }
            entityOrder.setBorder_uid_pay(entityOrder.getBorder_uid());
            entityOrder.setBorder_deposit(vo.getPay_deposit()); //支付订金
            entityOrder.setBorder_pay01_order_id(entityOrder.getBorder_id());
            if (vo.getPay_deposit() > 0) { //使用押金，订单有2个支付订单号
                entityOrder.setBorder_pay01_order_id(XApp.getStrID("OB"));
            }

            entityOrder.setBorder_user_name(vo.getUser_name());
            entityOrder.setBorder_user_phone(vo.getUser_phone());
            //spu
            entityOrder.setBorder_store_id(entitySpu.getBspu_store_id());
            entityOrder.setBorder_store_name(entityStore.getBstore_name());
            entityOrder.setBorder_spu_id(vo.getSpu_id());
            entityOrder.setBorder_spu_name(entitySpu.getBspu_name());
            entityOrder.setBorder_spu_count(vo.getSpu_count().longValue());
            //sku
            entityOrder.setBorder_sku_id(entitySku.getKey());
            entityOrder.setBorder_sku_day_price(entitySku.getBsku_day_price());
            //
            entityOrder.setBorder_sku_user_count(entitySpu.getBspu_user_count()); //几人房
            //set
            entityOrder.setBorder_set_id(vo.getSet_id());
            entityOrder.setBorder_set_name(entitySet.getBset_name());
            entityOrder.setBorder_set_day_price(entitySet.getBset_day_price());
            entityOrder.setBorder_set_user_count(vo.getSet_user_count()); //用餐人数
            //日期
            entityOrder.setBorder_date_begin(dateBegin);
            entityOrder.setBorder_date_end(dateEnd);
            entityOrder.setBorder_date_end_final(entityOrder.getBorder_date_end());
            entityOrder.setBorder_day(vo.getDay_count());
            entityOrder.setBorder_day_final(vo.getDay_count());
            entityOrder.setBorder_edit(0); //订单修改标记
            entityOrder.setBorder_enable(1);
            //
            entityOrder.setBorder_desc(vo.getDesc());

            if (vo.getContinue_order()) { //续单
                BookOrder entityOrderContinue = getApp().getEntity(vo.getContinue_main_id());

                entityOrder.setBorder_continue(1);
                entityOrder.setBorder_continue_main_id(vo.getContinue_main_id());
                entityOrder.setBorder_uid(entityOrderContinue.getBorder_uid());
                entityOrder.setBorder_uid_order(getUid());
                entityOrder.setBorder_uid_pay(entityOrder.getBorder_uid());
            }

            //数据处理
            orderHandle.handle(entityOrder);
            getApp().save(entityOrder);

            log.setLogMsg("支付订单创建");
            Integer expireMinutes = 10;
            if (vo.getContinue_order()) {
                expireMinutes = 60 * 24;
            }
            newPayOrder(entityOrder, "预订" + entitySpu.getBspu_name(), expireMinutes);

            XReturn r = XReturn.getR(0);
            r.setData("entity", entityOrder);
            return r;
        });
    }

    /**
     * 尾款下单
     *
     * @param vo
     */
    public XReturn order01(VoBookOrder01 vo) {
        BookOrder entityOrder = getApp().getEntity(vo.getOrder_id());
        XValidator.isNull(entityOrder, "订单号异常");
        if (!entityOrder.getBorder_uid().equals(getUid())) {
            return XReturn.getR(20278, "支付用户与下单用户不一致");
        }
        if (entityOrder.getBorder_status() < 5) {
            return XReturn.getR(20288, "订单未支付");
        }
        if (entityOrder.matchPayPriceLeft().compareTo(BigDecimal.ZERO) <= 0) {
            return XReturn.getR(20298, "金额已付清");
        }

        SysOrder entity = SysOrderService.getBean().getEntity(entityOrder.getBorder_pay01_order_id());
        if (entity == null) {
            entity = newPayOrder01(entityOrder, "付尾款");
        }

        XReturn r = XReturn.getR(0);
        r.setData("entity", entity);

        return r;
    }

    /**
     * 支付押金订单
     *
     * @param entityOrder
     * @param desc
     */
    protected SysOrder newPayOrder(BookOrder entityOrder, String desc, Integer expireMinutes) {
        SysOrder entity = new SysOrder();
        entity.setOrder_id(entityOrder.getKey());
        entity.setOrder_app_id("app_book");
        entity.setOrder_x_id(entityOrder.getBorder_x_id());
        entity.setOrder_uid(entityOrder.getBorder_uid());
        entity.setOrder_openid(SvcSysUser.getBean().getOpenid(entityOrder.getBorder_uid(), true));
        //订单过期时间
        LocalDateTime expireTime = LocalDateTime.now().plusMinutes(expireMinutes);
        entity.setOrder_pay_expire_date(expireTime);
        //金额
        entity.setOrder_price(entityOrder.getBorder_price_final());
        entity.setOrder_pay_price(entityOrder.getBorder_price_pay());
        entity.setOrder_desc(desc);
        entity.setOrder_id_00(entityOrder.getKey());
        SysOrderService.getBean().save(entity);

        return entity;
    }

    /**
     * 支付尾款订单
     *
     * @param entityOrder
     * @param desc
     */
    protected SysOrder newPayOrder01(BookOrder entityOrder, String desc) {
        SysOrder entity = new SysOrder();
        entity.setOrder_id(entityOrder.getBorder_pay01_order_id());
        entity.setOrder_app_id("app_book");
        entity.setOrder_x_id(entityOrder.getBorder_x_id());
        entity.setOrder_uid(entityOrder.getBorder_uid());
        entity.setOrder_openid(SvcSysUser.getBean().getOpenid(entityOrder.getBorder_uid(), true));
        //尾款订单不会过期
        LocalDateTime expireTime = XDate.now().plusYears(1);
        entity.setOrder_pay_expire_date(expireTime);
        //金额
        entity.setOrder_price(entityOrder.getBorder_price_final());
        entity.setOrder_pay_price(entityOrder.matchPayPriceLeft()); //支付剩余金额
        entity.setOrder_desc(desc);
        entity.setOrder_id_00(entityOrder.getKey());
        SysOrderService.getBean().save(entity);

        BookOrder entityUpdate = new BookOrder();
        entityUpdate.setBorder_id(entityOrder.getKey());
        entityUpdate.setBorder_price_pay01(entityOrder.matchPayPriceLeft()); //更新支付金额
        SvcBookOrder.getApp().updateById(entityUpdate);

        return entity;
    }

    //订单确认
    public XReturn confirm(VaBookOrderConfirm vo) {
        XValidator.checkTransaction();

        BookOrder entityOrder = getApp().getEntity(vo.getId());
        XValidator.isNull(entityOrder, "订单号异常");
        if (entityOrder.getBorder_status() != 5) {
            return XReturn.getR(20366, "订单状态异常，可能未支付");
        }
        if (vo.getConfirm() == 1) { //确认
            updateStatus(entityOrder, 10);
        } else { //拒绝，退款
            updateStatus(entityOrder, 7);
            //退款
            refundApplyAndAudit(VoBookOrderRefundApplyAndAudit.of(entityOrder.getKey()
                    , entityOrder.getBorder_price_pay_total()
                    , "后台订单确认操作-取消"));
        }

        return EnumSys.OK.getR();
    }

    //订单修改
    public XReturn orderEdit(VoBookOrderEdit vo) {
        BookOrder entityOrder = getApp().getEntity(vo.getOrder_id());
        XValidator.isNull(entityOrder, "订单号异常");
        if (entityOrder.matchPayPriceLeft().compareTo(BigDecimal.ZERO) <= 0) {
            return XReturn.getR(20061, "订单已付尾款，无法修改");
        }
        if (entityOrder.getBorder_continue() == 1) {
            return XReturn.getR(20071, "续单无法修改");
        }
        LocalDateTime dateBegin = XDate.toDate(XDate.parse(vo.getDate_begin()));
        if (dateBegin.isBefore(XDate.today())) {
            return XReturn.getR(20081, "入住时间不能小于当天");
        }
        //
        if (XStr.isNullOrEmpty(vo.getSet_id())) {
            vo.setSet_id(entityOrder.getBorder_set_id());
        }
        //
        VoBookOrder voOrder = new VoBookOrder();
        XBean.copyProperties(vo, voOrder);
        voOrder.setDate_begin(dateBegin);
        voOrder.setSpu_id(entityOrder.getBorder_spu_id());
        voOrder.setSet_id(vo.getSet_id());
        //
        XReturn r = orderCan(voOrder, true);
        XValidator.err(r);
        //
        BookSpu entitySpu = SvcBookSpu.getApp().getEntity(entityOrder.getBorder_spu_id());
        BookSku entitySku = SvcBookSku.getApp().getEntity(vo.getSku_id());
        BookSet entitySet = SvcBookSet.getApp().getEntity(vo.getSet_id());
        //
        LocalDateTime dateEnd = dateBegin.plusDays(vo.getDay_count() - 1);
        List<SpuDayData> listDay = SvcBookSpu.getBean().listDay(entitySpu, dateBegin, dateEnd);
        //
        BookOrderHandle orderHandle = BookOrderHandle.of();
        orderHandle.setVo(voOrder);
        orderHandle.setListDay(listDay);
        //
        return XApp.getTransaction().execute(status -> {
            SvcBookSpu.getApp().getEntityLock(entitySpu.getKey()); //锁房间
            //返回库存
            stockHandle(entitySpu, entityOrder.getBorder_date_begin(), entityOrder.getBorder_date_end(), -entityOrder.getBorder_spu_count().intValue());
            //检查库存
            {
                XReturn rr = stockCheck(entitySpu, dateBegin, dateEnd, vo.getSpu_count());
                XValidator.err(rr);
            }
            //扣库存
            stockHandle(entitySpu, dateBegin, dateEnd, vo.getSpu_count());
            //
            BookOrder entityOrderUpdate = new BookOrder();
            //修改支付订单号
            entityOrderUpdate.setBorder_pay01_order_id(XApp.getStrID("OB"));
            //spu
            entityOrderUpdate.setBorder_spu_count(vo.getSpu_count().longValue());
            //sku
            entityOrderUpdate.setBorder_sku_id(entitySku.getKey());
            entityOrderUpdate.setBorder_sku_day_price(entitySku.getBsku_day_price());
            entityOrderUpdate.setBorder_sku_user_count(entitySpu.getBspu_user_count()); //入住人数
            //set
            entityOrderUpdate.setBorder_set_id(vo.getSet_id()); //用餐ID
            entityOrderUpdate.setBorder_set_name(entitySet.getBset_name());
            entityOrderUpdate.setBorder_set_day_price(entitySet.getBset_day_price());
            entityOrderUpdate.setBorder_set_user_count(vo.getSet_user_count()); //用餐人数
            //entityOrderUpdate.setBorder_set_day_price(entityOrder.getBorder_set_day_price());

            //日期
            entityOrderUpdate.setBorder_date_begin(dateBegin);
            entityOrderUpdate.setBorder_date_end(dateEnd);
            entityOrderUpdate.setBorder_date_end_final(dateEnd);
            entityOrderUpdate.setBorder_day(vo.getDay_count());
            entityOrderUpdate.setBorder_day_final(vo.getDay_count());
            entityOrderUpdate.setBorder_edit(1); //标记已修改
            entityOrderUpdate.setBorder_edit_date(XDate.now());
            //赋值分账数据，计算分账
            entityOrderUpdate.setBorder_deposit_price(entityOrder.getBorder_deposit_price());
            entityOrderUpdate.setBorder_price_pay(entityOrder.getBorder_price_pay());
            entityOrderUpdate.setBorder_share_app_rate(entityOrder.getBorder_share_app_rate());
            entityOrderUpdate.setBorder_share_sales_rate(entityOrder.getBorder_share_sales_rate());
            //
            //数据处理
            orderHandle.handle(entityOrderUpdate);
            getApp().saveOrUpdatePassEqualField(entityOrder, entityOrderUpdate);

            return EnumSys.OK.getR();
        });
    }

    //订单续单
    public XReturn orderContinue(VoBookOrderContinue vo) {
        BookOrder entityOrder = getApp().getEntity(vo.getOrder_id());
        XValidator.isNull(entityOrder, "订单号异常");
        if (entityOrder.getBorder_status() != 15) {
            return XReturn.getR(20590, "订单未入住中，无法续单");
        }
        if (entityOrder.getBorder_continue() == 1) {
            return XReturn.getR(20600, "非主订单");
        }
        //存在未入住续单，不能下单
        {
            JoinWrapperPlus<BookOrder> query = listQuery();
            query.eq("border_continue_main_id", entityOrder.getKey())
                    .eq("border_continue", 1)
                    .in("border_status", 0, 5, 10, 15)
                    .ge("border_date_begin", XDate.today())
                    .in("border_refund", 0, 10)
            ;
            query.select("1");
            Map<String, Object> mapOrder = getApp().firstMap(query);
            if (mapOrder != null) {
                return XReturn.getR(20610, "已存在续单，请处理后再下单");
            }
        }

        int dayTotal = entityOrder.getBorder_day_final() + vo.getDay_count(); //续单（主单+续单）天数
        BookSku entitySku = SvcBookSku.getBean().getEntitySku(entityOrder.getBorder_spu_id(), dayTotal);

        VoBookOrder voOrder = new VoBookOrder();
        voOrder.setSpu_id(entityOrder.getBorder_spu_id());
        voOrder.setSet_id(entityOrder.getBorder_set_id());
        voOrder.setSku_id(entitySku.getKey());
        voOrder.setDate_begin(entityOrder.getBorder_date_end_final().plusDays(1));
        voOrder.setDay_count(vo.getDay_count());
        voOrder.setUser_name(entityOrder.getBorder_user_name());
        voOrder.setUser_phone(entityOrder.getBorder_user_phone());
        voOrder.setSpu_count(entityOrder.getBorder_spu_count().intValue());
        voOrder.setSet_user_count(vo.getSet_user_count());
        voOrder.setPay_deposit(0);
        voOrder.setSale_uid(vo.getSale_uid());
        voOrder.setContinue_order(true);
        voOrder.setContinue_main_id(entityOrder.getKey());
        XReturn r = order(voOrder);
        if (r.err()) {
            return r;
        }

        return r;
    }


    //确认入住
    public XReturn checkin(VaBookOrderCheckin vo) {
        XValidator.checkTransaction();

        List<BookOrder> listOrder = getApp().get(vo.getIds());
        for (BookOrder entityOrder : listOrder) {
            if (entityOrder.getBorder_date_begin().isAfter(XDate.now())) {
                return XReturn.getR(20264, entityOrder.getBorder_id() + "：未到时间入住");
            }
            if (entityOrder.matchPayPriceLeft().compareTo(BigDecimal.ZERO) > 0) {
                if (vo.getSpu_pay() == 0) { //线上付房费
                    XValidator.err(20330, entityOrder.getBorder_id() + "：支付金额未付清，无法入住");
                }
            }

            VaBookOrderUpdateStatus updateStatus = VaBookOrderUpdateStatus.of(15, "");
            updateStatus.setSpu_pay(vo.getSpu_pay());
            updateStatus(entityOrder, updateStatus);

            if (vo.getSpu_pay() == 1) { //房费线下支付,佣金归0
                BookOrder entityOrderUpdate = new BookOrder();
                entityOrderUpdate.setBorder_price_share_final(BigDecimal.ZERO);
                //为了计算，需要赋值
                entityOrderUpdate.setBorder_share_app_rate(entityOrder.getBorder_share_app_rate());
                entityOrderUpdate.setBorder_share_sales_rate(entityOrder.getBorder_share_sales_rate());
                entityOrderUpdate.setBorder_price_down_fun(entityOrder.getBorder_price_down_fun());
                BookOrderHandle90SharePrice.matchSharePrice(entityOrderUpdate);
                getApp().saveOrUpdatePassEqualField(entityOrder, entityOrderUpdate);
            }
        }

        return EnumSys.OK.getR();
    }

    //退房
    public XReturn checkout(VaBookOrderCheckout vo) {
        XValidator.checkTransaction();

        BookOrder entityOrder = getApp().getEntity(vo.getId());
        XValidator.isNull(entityOrder, "订单号异常");
        //if (entityOrder.getBorder_deposit() == 0) {
        //    vo.setRefund_price(BigDecimal.ZERO);
        //} else {
        //    if (vo.getRefund_price().compareTo(entityOrder.getBorder_deposit_price()) > 0) {
        //        return XReturn.getR(20408, "退款金额大于押金金额");
        //    }
        //}

        updateStatus(entityOrder, 20);

        if (vo.getRefund_price().compareTo(BigDecimal.ZERO) > 0) {
            refundApplyAndAudit(VoBookOrderRefundApplyAndAudit.of(entityOrder.getKey()
                    , vo.getRefund_price()
                    , "后台退房操作"));
        }

        return EnumSys.OK.getR();
    }


    /**
     * 申请退款并通过
     *
     * @param vo
     */
    public XReturn refundApplyAndAudit(VoBookOrderRefundApplyAndAudit vo) {
        String refundId;
        log.debug("退款申请");
        {
            VoBookOrderRefundApply voApply = new VoBookOrderRefundApply();
            voApply.setOrder_id(vo.getOrder_id());
            voApply.setApply_desc(vo.getApply_desc());
            voApply.setPriceDown0(true);
            voApply.setAdmin(true);
            voApply.setApply_price(vo.getRefund_price());
            XReturn r = refundApply(voApply);
            XValidator.err(r);

            refundId = r.getData("refund_id");
        }
        log.debug("退款审核通过");
        {
            VoBookOrderRefundAudit voAudit = new VoBookOrderRefundAudit();
            voAudit.setRefund_id(refundId);
            voAudit.setRefund_price(vo.getRefund_price());
            voAudit.setAudit_status(1);
            XReturn r = refundAudit(voAudit);
            XValidator.err(r);
        }

        return EnumSys.OK.getR();
    }

    /**
     * 申请退款
     *
     * @param vo
     */
    public XReturn refundApply(VoBookOrderRefundApply vo) {
        BookOrder entityOrder = getApp().getEntity(vo.getOrder_id());
        XValidator.isNull(entityOrder, "订单号异常");

        if (entityOrder.getBorder_status() < 5) {
            return XReturn.getR(20288, "订单未支付");
        }
        if (entityOrder.getBorder_refund() != 0) {
            return XReturn.getR(20298, "订单已申请退款");
        }
        if (!vo.getAdmin()) {
            if (entityOrder.getBorder_status() >= 20) {
                return XReturn.getR(20308, "已退房");
            }
        }


        BookStore entityStore = SvcBookStore.getApp().getEntity(entityOrder.getBorder_store_id());
        XValidator.isNull(entityStore, "基地已删除");
        BigDecimal refundRate = SvcBookStore.getBean().getRefundRate(entityStore.getKey(), entityOrder.getBorder_date_begin()); //费率

        BigDecimal refundPriceDown = BigDecimal.ZERO; //退款手续费
        if (!vo.getPriceDown0()) {
            if (refundRate.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal rate = refundRate.divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
                refundPriceDown = entityOrder.getBorder_price_spu().multiply(rate);
                refundPriceDown = XApp.toDecimalPay(refundPriceDown);
            }
            if (refundPriceDown.compareTo(entityOrder.getBorder_price_pay_total()) > 0) { //退款手续费大于总支付金额
                refundPriceDown = entityOrder.getBorder_price_pay_total();
            }
        }

        BigDecimal refundPriceDownX = refundPriceDown;

        return XApp.getTransaction().execute(status -> {
            BigDecimal refundApplyPrice = entityOrder.getBorder_price_pay_total().subtract(refundPriceDownX); //申请退款金额
            if (refundApplyPrice.compareTo(BigDecimal.ZERO) < 0) {
                refundApplyPrice = BigDecimal.ZERO; //可能会扣爆，如：付了押金退款的情况
            }
            if (vo.getAdmin()) { //后台退款可指定退款金额
                if (vo.getApply_price() != null) {
                    refundApplyPrice = vo.getApply_price();
                }
            }

            BookRefundOrder entityRefund = new BookRefundOrder();
            entityRefund.setAutoID();
            entityRefund.setBrefo_x_id(entityOrder.getBorder_x_id());
            entityRefund.setBrefo_order_id(entityOrder.getKey());
            entityRefund.setBrefo_key(entityOrder.getKey());
            entityRefund.setBrefo_order_id01(entityOrder.getBorder_pay01_order_id());
            entityRefund.setBrefo_price_pay00(entityOrder.getBorder_price_pay());
            entityRefund.setBrefo_price_pay01(entityOrder.getBorder_price_pay01());
            entityRefund.setBrefo_price_pay(entityOrder.getBorder_price_pay());
            entityRefund.setBrefo_refund_id00(entityOrder.getKey());
            entityRefund.setBrefo_refund_id01(entityOrder.getBorder_pay01_order_id());
            entityRefund.setBrefo_store_id(entityOrder.getBorder_store_id());
            entityRefund.setBrefo_uid(entityOrder.getBorder_uid());
            entityRefund.setBrefo_apply_price(refundApplyPrice); //申请退款金额
            entityRefund.setBrefo_apply_desc(vo.getApply_desc()); //申请描述
            entityRefund.setBrefo_down_rate(refundRate);//手续费率
            entityRefund.setBrefo_price_down(refundPriceDownX); //手续费
            BookRefundOrderService.getBean().save(entityRefund);

            BookOrder entityOrderUpdate = new BookOrder();
            entityOrderUpdate.setBorder_id(entityOrder.getKey());
            entityOrderUpdate.setBorder_refund(10);
            entityOrderUpdate.setBorder_refund_date(XDate.now());
            SvcBookOrder.getApp().updateById(entityOrderUpdate);

            XReturn r = EnumSys.OK.getR();
            r.setData("refund_id", entityRefund.getKey());
            return r;
        });
    }

    /**
     * 退款审核
     *
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    public XReturn refundAudit(VoBookOrderRefundAudit vo) {
        BookRefundOrder entityOrderRefund = BookRefundOrderService.getBean().first(vo.getRefund_id());
        XValidator.isNull(entityOrderRefund, "退款订单ID异常");
        if (entityOrderRefund.getBrefo_audit_status() != 0) {
            return XReturn.getR(20356, "已审核");
        }
        //锁订单
        BookOrder entityBookOrder = SvcBookOrder.getApp().getEntityLock(entityOrderRefund.getBrefo_order_id());
        XValidator.isNull(entityOrderRefund, "订单不存在");
        if (vo.getAudit_status() == 1) {
            BigDecimal pricePayTotal = entityBookOrder.getBorder_price_pay_total().subtract(entityBookOrder.getBorder_price_pay_total_lock());
            if (vo.getRefund_price().compareTo(pricePayTotal) > 0) {
                return XReturn.getR(20366, "退款金额不能大于支付金额，" + pricePayTotal);
            }
        }

        //更新退款订单审核状态
        BookRefundOrder entityOrderRefundUpdate = new BookRefundOrder();
        entityOrderRefundUpdate.setBrefo_id(entityOrderRefund.getKey());
        entityOrderRefundUpdate.setBrefo_audit_status(vo.getAudit_status());
        entityOrderRefundUpdate.setBrefo_audit_status_date(XDate.now());
        entityOrderRefundUpdate.setBrefo_audit_desc(vo.getAudit_desc());
        if (vo.getAudit_status() == 1) { //审核通过
            BigDecimal refundPriceTotal = vo.getRefund_price();

            if (entityBookOrder.getBorder_price_pay().compareTo(refundPriceTotal) > 0) { //第1次支付
                entityOrderRefundUpdate.setBrefo_refund_price00(vo.getRefund_price());
                refundPriceTotal = BigDecimal.ZERO;
            } else {
                entityOrderRefundUpdate.setBrefo_refund_price00(entityBookOrder.getBorder_price_pay());
                refundPriceTotal = refundPriceTotal.subtract(entityBookOrder.getBorder_price_pay());
            }
            if (entityBookOrder.getBorder_price_pay01().compareTo(refundPriceTotal) > 0) { //第2次支付
                entityOrderRefundUpdate.setBrefo_refund_price01(refundPriceTotal);
            } else {
                entityOrderRefundUpdate.setBrefo_refund_price01(entityBookOrder.getBorder_price_pay01());
            }
            //总退款金额
            entityOrderRefundUpdate.setBrefo_refund_price(entityOrderRefundUpdate.getBrefo_refund_price00()
                    .add(entityOrderRefundUpdate.getBrefo_refund_price01()));
        } else { //不通过，修改key唯一
            entityOrderRefundUpdate.setBrefo_key(XApp.getStrID());
        }
        BookRefundOrderService.getBean().saveOrUpdatePassEqualField(entityOrderRefund, entityOrderRefundUpdate);

        //更新订单状态
        BookOrder entityOrderUpdate = new BookOrder();
        entityOrderUpdate.setBorder_id(entityOrderRefund.getBrefo_order_id());
        if (vo.getAudit_status() == 10) { //不通过
            entityOrderUpdate.setBorder_refund(0);
            entityOrderUpdate.setBorder_refund_date(XDate.date2000());
        } else { //通过
            entityOrderUpdate.setBorder_refund(1);
            entityOrderUpdate.setBorder_refund_date(XDate.now());
            BigDecimal shareFinalPrice = BigDecimal.ZERO; //入住前退款不分帐
            if (entityBookOrder.getBorder_status() > 10) { //入住后退款分帐
                //入住后退款，重新计算分摊金额
                //总支付金额 - 退款金额
                //大于房费，拿房费分帐，
                //小于房费，拿剩余分账
                shareFinalPrice = entityBookOrder.getBorder_price_pay_total()
                        .subtract(vo.getRefund_price());
                if (shareFinalPrice.compareTo(entityBookOrder.matchSharePrice()) > 0) {
                    shareFinalPrice = entityBookOrder.matchSharePrice();
                }
            }
            entityOrderUpdate.setBorder_price_share_final(shareFinalPrice);
            //为了计算，需要赋值
            entityOrderUpdate.setBorder_share_app_rate(entityBookOrder.getBorder_share_app_rate());
            entityOrderUpdate.setBorder_share_sales_rate(entityBookOrder.getBorder_share_sales_rate());
            entityOrderUpdate.setBorder_price_down_fun(entityBookOrder.getBorder_price_down_fun());
            BookOrderHandle90SharePrice.matchSharePrice(entityOrderUpdate);
        }
        SvcBookOrder.getApp().saveOrUpdatePassEqualField(entityBookOrder, entityOrderUpdate);

        if (vo.getAudit_status() == 1) { //通过处理
            //返还库存
            log.debug("库存释放");
            VaBookSpuDayUpdateStock stockUpdate = VaBookSpuDayUpdateStock.of(entityBookOrder.getBorder_spu_id()
                    , entityBookOrder.getBorder_date_begin()
                    , entityBookOrder.getBorder_date_end_final()
                    , -entityBookOrder.getBorder_spu_count().intValue());
            SvcBookSpu.getBean().dayBatchUpdateStock(stockUpdate);

            if (entityBookOrder.getBorder_price_down_fun().compareTo(BigDecimal.ZERO) > 0
                    && entityBookOrder.getBorder_status() <= 10 //入住前，全退积分，否则不退
            ) {
                log.debug("退积分");
                VaFunAdd vaFunAdd = VaFunAdd.of("refund|" + entityBookOrder.getKey()
                        , entityBookOrder.getBorder_uid()
                        , entityBookOrder.getKey()
                        , "app_book"
                        , BookOrderHandle20FunDown.money2Fun(entityBookOrder.getBorder_price_down_fun())
                        , "房间预订-退款");
                vaFunAdd.setUpdate_fun(true);
                SvcFun.getBean().add(vaFunAdd);
            }

            if (entityBookOrder.getBorder_status() >= 10) { //确认订单后退款，需要主订单减金额
                log.debug("续单");
                if (entityBookOrder.getBorder_continue() == 1) {
                    updateOrderMain(entityBookOrder, false);
                }
            }
        }

        return EnumSys.OK.getR();
    }

    /**
     * 根据订单号，退款api操作
     * 会try掉
     *
     * @param orderId
     */
    public XReturn refundByOrderID(String orderId) {
        BookRefundOrder entityOrderRefund = getEntityRefund(orderId);
        XValidator.isNull(entityOrderRefund, "订单未申请退款异常");

        try {
            refund(entityOrderRefund.getKey());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            ex.printStackTrace();
        }
        return EnumSys.OK.getR();
    }

    /**
     * 退款
     *
     * @param refundId
     */
    public XReturn refund(String refundId) {
        BookRefundOrder entityOrderRefund = BookRefundOrderService.getBean().first(refundId);
        XValidator.isNull(entityOrderRefund, "退款订单ID异常");
        if (entityOrderRefund.getBrefo_refund_handle() == 1) {
            return XReturn.getR(20500, "已退款");
        }
        if (entityOrderRefund.getBrefo_audit_status() != 1) {
            return XReturn.getR(20510, "退款订单审核不通过");
        }
        if (entityOrderRefund.getBrefo_refund_price().compareTo(BigDecimal.ZERO) <= 0) { //退款金额为0,无需退款
            return EnumSys.OK.getR();
        }

        SysOrder entityOrder = SysOrderService.getBean().getEntity(entityOrderRefund.getBrefo_order_id());
        XValidator.isNull(entityOrder, "支付订单号异常");

        //接口退款
        Boolean refund0 = true;
        WxApiPay api = WxApiPay.getIns(XHttpContext.getXConfig());
        String errmsg = "";
        if (entityOrderRefund.getBrefo_refund_price00().compareTo(BigDecimal.ZERO) > 0) {
            log.debug("第1次退款");
            XReturn r = api.orderRefundInfo(entityOrderRefund.getBrefo_refund_id00());
            if (r.err()) {
                refund0 = false;
                Long orderFee = XApp.decimalToFee(entityOrderRefund.getBrefo_price_pay00());
                Long refundFee = XApp.decimalToFee(entityOrderRefund.getBrefo_refund_price00());
                XReturn rr = api.orderRefund(entityOrderRefund.getBrefo_order_id(), entityOrderRefund.getBrefo_refund_id00(), orderFee, refundFee);
                errmsg += rr.getErrMsg();
                if (rr.ok()) {
                    refund0 = true;
                }
            }
        }

        Boolean refund1 = true;
        if (entityOrderRefund.getBrefo_refund_price01().compareTo(BigDecimal.ZERO) > 0) {
            log.debug("第2次退款");
            XReturn r = api.orderRefundInfo(entityOrderRefund.getBrefo_refund_id01());
            if (r.err()) {
                refund1 = false;
                Long orderFee = XApp.decimalToFee(entityOrderRefund.getBrefo_price_pay01());
                Long refundFee = XApp.decimalToFee(entityOrderRefund.getBrefo_refund_price01());
                XReturn rr = api.orderRefund(entityOrderRefund.getBrefo_order_id01(), entityOrderRefund.getBrefo_refund_id01(), orderFee, refundFee);
                errmsg += "，" + rr.getErrMsg();
                if (rr.ok()) {
                    refund1 = true;
                }
            }
        }


        BookRefundOrder entityOrderRefundUpdate = new BookRefundOrder();
        XReturn r = XReturn.getR(0);
        if (refund0 && refund1) {
            entityOrderRefundUpdate.setBrefo_refund_handle(1);
        } else {
            r.setErrCode(20168);
            r.setErrMsg(errmsg);

            entityOrderRefundUpdate.setBrefo_refund_handle(10);
        }
        entityOrderRefundUpdate.setBrefo_refund_errmsg(errmsg);
        entityOrderRefundUpdate.setBrefo_refund_handle_date(XDate.now());
        BookRefundOrderService.getBean().saveOrUpdatePassEqualField(entityOrderRefund, entityOrderRefundUpdate);

        return r;
    }

    public void updateStatus(BookOrder entityOrder, Integer status) {
        updateStatus(entityOrder, VaBookOrderUpdateStatus.of(status, ""));
    }

    /**
     * 更新订单状态
     *
     * @param entityOrder
     */
    public void updateStatus(BookOrder entityOrder, VaBookOrderUpdateStatus vo) {
        XValidator.checkTransaction();

        if (vo.getStatus() <= entityOrder.getBorder_status()) {
            XValidator.err(20256, "操作异常，订单状态不能回退");
        }

        BookOrder entityOrderUpdate = new BookOrder();
        entityOrderUpdate.setBorder_id(entityOrder.getKey());
        entityOrderUpdate.setBorder_status(vo.getStatus());

        switch (vo.getStatus()) {
            case 3: //关闭订单
                entityOrderUpdate.setBorder_enable(0);
                break;
            case 5: //已支付
                //发短信
                BookStore entityStore = SvcBookStore.getApp().getEntity(entityOrder.getBorder_store_id());
                String smsIdPay = SvcBookSetting.getBean().getSettingTxt00().getSms_pay();
                if (XStr.hasAnyText(smsIdPay)) {
                    VoSmsSend voSmsSend = VoSmsSend.of(smsIdPay, entityOrder.getBorder_uid());
                    voSmsSend.addReplace("{name}", entityOrder.getBorder_user_name());
                    voSmsSend.addReplace("{money}", entityOrder.getBorder_price_pay().toString());
                    voSmsSend.addReplace("{hotel}", entityStore.getBstore_title());
                    voSmsSend.addReplace("{roomtype}", entityOrder.getBorder_sku_user_count() + "人房");
                    SvcSms.getBean().send(voSmsSend);
                }
                break;
            case 7: //确认拒绝
            case 10: //待入住
                entityOrderUpdate.setBorder_confirm(1);
                if (vo.getStatus() == 7) {
                    entityOrderUpdate.setBorder_confirm(10); //标记拒绝
                }
                entityOrderUpdate.setBorder_confirm_date(XDate.now());
                entityOrderUpdate.setBorder_confirm_desc(vo.getDesc());
                //
                if (entityOrder.getBorder_continue() == 1) { //续单
                    if (vo.getStatus() == 10) { //确认直接入住中
                        entityOrderUpdate.setBorder_status(15);
                        entityOrderUpdate.setBorder_checkin(1);
                        entityOrderUpdate.setBorder_checkin_date(XDate.now());

                        updateOrderMain(entityOrder, true);
                    }
                }
                break;
            case 15: //入住中
                entityOrderUpdate.setBorder_checkin(1);
                entityOrderUpdate.setBorder_checkin_date(XDate.now());
                entityOrderUpdate.setBorder_spu_pay(vo.getSpu_pay());
                break;
            case 20: //已退房
                entityOrderUpdate.setBorder_checkout(1);
                entityOrderUpdate.setBorder_checkout_date(XDate.now());

                if (entityOrder.getBorder_continue() == 0) { //主单已退房，续单全部标记退房
                    getApp().update()
                            .set("border_checkout", 1)
                            .set("border_checkout_date", XDate.now())
                            .set("border_status", 20)
                            .eq("border_continue_main_id", entityOrder.getKey())
                            .eq("border_status", 15)
                            .update();

                }
                break;
        }
        getApp().saveOrUpdatePassEqualField(entityOrder, entityOrderUpdate);

        //更新待确认订单数量
        {
            JoinWrapperPlus<BookOrder> query = listQuery();
            query.eq("border_status", 5)
                    .eq("border_store_id", entityOrder.getBorder_store_id());
            Long order5Count = getApp().count(query);
            BookStore entityStoreUpdate = new BookStore();
            entityStoreUpdate.setBstore_id(entityOrder.getBorder_store_id());
            entityStoreUpdate.setBstore_order5_count(order5Count);
            SvcBookStore.getApp().updateById(entityStoreUpdate);
        }
    }

    /**
     * 更新主订单数据
     *
     * @param entityOrderContinue 续订单
     * @param add                 【true】增加；【false】减少；
     */
    public void updateOrderMain(BookOrder entityOrderContinue, Boolean add) {
        if (entityOrderContinue.getBorder_continue() != 1) { //非续单pass
            return;
        }

        //续单确认订单，更新主单金额处理
        BookOrder entityMain = getApp().getEntity(entityOrderContinue.getBorder_continue_main_id());
        if (add) { //增加
            getApp().update()
                    .setSql("border_continue_price_total = border_continue_price_total + " + entityOrderContinue.getBorder_price_final()) //续单总金额
                    .setSql("border_continue_day_total = border_continue_day_total + " + entityOrderContinue.getBorder_day_final()) //续单总天数
                    //.setSql("border_day_final = border_day_final + " + entityOrderContinue.getBorder_day_final()) //延长主订单退房时间
                    //.set("border_date_end_final", entityMain.getBorder_date_end_final().plusDays(entityOrderContinue.getBorder_day_final())) //延长主订单退房时间
                    .eq(BookOrder.tableKey(), entityOrderContinue.getBorder_continue_main_id())
                    .update();
        } else { //减少
            getApp().update()
                    .setSql("border_continue_price_total = border_continue_price_total - " + entityOrderContinue.getBorder_price_final()) //续单总金额
                    .setSql("border_continue_day_total = border_continue_day_total - " + entityOrderContinue.getBorder_day_final()) //续单总天数
                    //.setSql("border_day_final = border_day_final - " + entityOrderContinue.getBorder_day_final()) //延长主订单退房时间
                    //.set("border_date_end_final", entityMain.getBorder_date_end_final().minusDays(entityOrderContinue.getBorder_day_final())) //延长主订单退房时间
                    .eq(BookOrder.tableKey(), entityOrderContinue.getBorder_continue_main_id())
                    .update();
        }
    }

    /**
     * 商家分账
     * 订单积分赠送
     */
    public XReturn sharePrice(BookOrder entity) {
        if (entity.getBorder_status() != 20) {
            return XReturn.getR(20507, "订单未退房");
        }
        //if (entity.getBorder_share_sales_price().compareTo(BigDecimal.ZERO) > 0) { //主播分帐
        //    String key = "sale|" + entity.getKey();
        //    VoSaleAddRecord data = VoSaleAddRecord.of(key, entity.getBorder_share_sales_uid(), entity.getBorder_share_sales_price(), "订单完成", "app_book", entity.getKey());
        //    SvcSysSale.getBean().addRecord(data);
        //}

        if (entity.getBorder_share_store_price().compareTo(BigDecimal.ZERO) > 0) { //商家分账
            String key = "store|" + entity.getKey();
            VoSaleAddRecord data = VoSaleAddRecord.of(key, entity.getBorder_store_id(), entity.getBorder_share_store_price(), "订单完成", "app_book", entity.getKey());
            SvcSysSale.getBean().addRecord(data);
        }

        if (entity.getBorder_give_fun() > 0) {
            log.info("订单完成赠送积分");
            SvcFun.getBean().add("give_fun|" + entity.getKey(), entity.getBorder_give_uid(), entity.getKey(), "app_book", entity.getBorder_give_fun().intValue(), "订单完成赠送积分");
        }

        return EnumSys.OK.getR();
    }

    /**
     * 主播分帐
     *
     * @param entity
     */
    public XReturn shareSalesPrice(BookOrder entity) {
        XValidator.checkTransaction();

        if (entity.getBorder_status() < 15) {
            return EnumSys.ERR_VAL.getR("订单状态异常");
        }
        entity = SvcBookOrder.getApp().getEntityLock(entity.getKey()); //锁订单
        if (entity.getBorder_share_sales_price().compareTo(BigDecimal.ZERO) <= 0) {
            //无分帐
            return EnumSys.OK.getR();
        }

        BigDecimal shareSalesPriceLeft = entity.matchShareSalesPriceLeft();
        LogPipeLine.ofSys().setLogMsg("剩余可分账金额：" + shareSalesPriceLeft.toString());
        BigDecimal pricePayTotalLockLeft = entity.matchPricePayTotalLockLeft();
        LogPipeLine.ofSys().setLogMsg("剩余可锁定的订单支付金额：" + pricePayTotalLockLeft.toString());

        BigDecimal sharePrice1; //本次分账金额
        //本次锁定订单金额（房费）
        BigDecimal payPriceLock1 = entity.getBorder_price_spu() //房费（不含订金）
                .divide(BigDecimal.valueOf(entity.getBorder_day_final()), 2, RoundingMode.HALF_UP);
        if (payPriceLock1.compareTo(pricePayTotalLockLeft) > 0) { //大于剩余
            payPriceLock1 = pricePayTotalLockLeft;
        }
        LogPipeLine.ofSys().setLogMsg("本次锁定房费金额：", payPriceLock1.toString());

        if (entity.getBorder_status() == 20) {
            sharePrice1 = shareSalesPriceLeft;
            LogPipeLine.ofSys().setLogMsg("订单状态：已退房，剩余全部分，", sharePrice1.toString());
        } else {
            sharePrice1 = entity.getBorder_share_sales_price()
                    .divide(BigDecimal.valueOf(entity.getBorder_day_final()), 2, RoundingMode.HALF_UP);
            if (sharePrice1.compareTo(shareSalesPriceLeft) > 0) { //大于剩余金额
                sharePrice1 = shareSalesPriceLeft;
            }
            LogPipeLine.ofSys().setLogMsg("订单状态：入住中，按每日分，", sharePrice1.toString());
        }
        if (sharePrice1.compareTo(BigDecimal.ZERO) <= 0) { //已分账完成
            return EnumSys.OK.getR();
        }

        //更新订单金额
        getApp().update()
                .setSql("border_price_pay_total_lock = border_price_pay_total_lock + " + payPriceLock1)
                .setSql("border_share_sales_price_use = border_share_sales_price_use + " + sharePrice1)
                .eq("border_id", entity.getKey())
                .update();


        String key = XStr.format("sale|{0}|{1}", entity.getKey(), XDate.toDateString());
        VoSaleAddRecord data = VoSaleAddRecord.of(key
                , entity.getBorder_share_sales_uid()
                , sharePrice1
                , "订单分账-每日"
                , "app_book"
                , entity.getKey()
        );
        SvcSysSale.getBean().addRecord(data);

        return XReturn.getR(5);
    }

    /**
     * 更新支付金额
     *
     * @param entityBookOrder
     */
    public void updatePayPriceTotal(BookOrder entityBookOrder) {
        BookOrder entityUpdate = new BookOrder();
        entityUpdate.setBorder_id(entityBookOrder.getKey());
        entityUpdate.setBorder_price_pay_total(entityBookOrder.matchPaylPriceTotal()); //更新支付总金额
        SvcBookOrder.getApp().updateById(entityUpdate);
    }
}
